package com.jt.tenant.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.LinearLayout;

import com.jt.tenant.R;
import com.jt.tenant.app.JTApplication;
import com.jt.tenant.conn.GetAccountSettings;
import com.jt.tenant.dialog.MyTimePopup;
import com.jt.tenant.dialog.YouXiaoQiPopup;
import com.jt.tenant.fragment.MeFragment;
import com.jt.tenant.widget.Tools;
import com.module.round.RoundedImageView;
import com.zcx.helper.http.AsyCallBack;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Created by yzf on 2016/2/14.
 */
public class PersonInfoActivity extends JTV4Activity implements View.OnClickListener {

    private TextView title_name, commit;

    private MyTimePopup timePopupWindow;

    private Date date1;

    private RoundedImageView head_img1;

    public static SetHeadPicListener setHeadPicListener;

    private EditText edit_nickname, edit_car_num;

    private TextView edit_start_date;

    private EditText edit_validity_period;

    private RadioGroup rg_sex;

    private String sex = "1";//性别

    private RadioButton rb_man, rb_woman;

    private LinearLayout lin_car_num, lin_validity_period;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_person_info);

        init_view();

    }

    private void init_view() {

        (lin_car_num = (LinearLayout) findViewById(R.id.lin_car_num)).setOnClickListener(this);

        (lin_validity_period = (LinearLayout) findViewById(R.id.lin_validity_period)).setOnClickListener(this);

        (title_name = (TextView) findViewById(R.id.tv_title_name)).setText("个人中心");

        (commit = (TextView) findViewById(R.id.commit)).setOnClickListener(this);

        (head_img1 = (RoundedImageView) findViewById(R.id.head_img1)).setOnClickListener(this);

//        edit_phone = (EditText) findViewById(R.id.edit_phone);

        edit_nickname = (EditText) findViewById(R.id.edit_nickname);

        edit_car_num = (EditText) findViewById(R.id.edit_car_num);

//        edit_car_num.setKeyListener(new NumberKeyListener() {
//            @Override
//            protected char[] getAcceptedChars() {
//
//                char numberChars[]={'1','2','3','4','5','6','7','8','9','0','X'};
//
//                return numberChars;
//            }
//
//            @Override
//            public int getInputType() {
//                return 0;
//            }
//        });

        edit_start_date = (TextView) findViewById(R.id.edit_start_date);

        edit_validity_period = (EditText) findViewById(R.id.edit_validity_period);

        edit_validity_period.setOnClickListener(this);

        (rb_man = (RadioButton) findViewById(R.id.man)).setChecked(true);

        rb_woman = (RadioButton) findViewById(R.id.woman);

        timePopupWindow = new MyTimePopup(context, null, new Date(), MyTimePopup.Type.YEAR_MONTH_DAY){

            private SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");

            @Override
            public void onSubmit(Date date) {

                edit_start_date.setText(simpleDateFormat.format(date));

            }

        };

        (rg_sex = (RadioGroup) findViewById(R.id.sex)).setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {

                int radioButtonId = group.getCheckedRadioButtonId();

                switch (radioButtonId) {

                    //选中男
                    case R.id.man:

                        rb_man.setChecked(true);

                        sex = "1";

                        break;

                    //选中女
                    case R.id.woman:

                        rb_woman.setChecked(true);

                        sex = "2";

                        break;

                }

            }
        });

        //判断性别，将被选中项勾选上
        if (JTApplication.jtPreferences.readSex().equals("男")) {//男

            rb_man.setChecked(true);

        } else if (JTApplication.jtPreferences.readSex().equals("女")) {//女

            rb_woman.setChecked(true);

        }

        //设置信息
        JTApplication.UtilAsyncBitmap.get(JTApplication.jtPreferences.readHeadPath()+"?imageMogr2/thumbnail/132x132", head_img1,R.mipmap.iv_face);

        edit_nickname.setText(JTApplication.jtPreferences.readNickName());

        edit_car_num.setText(JTApplication.jtPreferences.readDriverNum());

        edit_start_date.setText(JTApplication.jtPreferences.readDriverEffectiveDate());

        edit_validity_period.setText(JTApplication.jtPreferences.readDriverEffectiveYear());

        setHeadPicListener = new SetHeadPicListener() {

            @Override
            public void setHeadPic(String setHeadPic) {

                JTApplication.UtilAsyncBitmap.get(setHeadPic, head_img1);

//                if(PersonageFragment.refreshListener != null){
//
//                    PersonageFragment.refreshListener.refresh(setHeadPic);

//                }

            }

        };

    }


    @Override
    public void onClick(View v) {

        switch (v.getId()) {

            case R.id.lin_car_num:

                //先关闭软键盘
                View view = getWindow().peekDecorView();

                if (view != null) {

                    InputMethodManager inputmanger = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);

                    inputmanger.hideSoftInputFromWindow(view.getWindowToken(), 0);

                }

                timePopupWindow.showAtLocation(v, Gravity.BOTTOM, 0, 0);

                break;

            case R.id.lin_validity_period:


                break;

            case R.id.commit:

//                final String phone = edit_phone.getText().toString().trim();

                final String nick_name = edit_nickname.getText().toString().trim();

                final String car_num = edit_car_num.getText().toString();

                final String start_date = edit_start_date.getText().toString();

                final String validity_period = edit_validity_period.getText().toString();

                //将图片路径存储到本地缓存 用来做接下来的 (选择头像->没提交->清空图片路径)
//                ChoosePicActivity.getHeadImgPathListener == null
                if (head_img1.getDrawable() == null || nick_name.equals("") || car_num.equals("") || start_date.equals("") ||
                        validity_period.equals("") || sex.equals("")) {

                    Toast.makeText(this, "请将信息填写完整", Toast.LENGTH_SHORT).show();

                } else if (!Tools.personIdValidation(car_num)) {

                    Toast.makeText(this, "驾驶证号格式不正确", Toast.LENGTH_SHORT).show();

                } else {

                    String head_img = null;
                    //headPic 给后台的图片url
                    if (ChoosePicActivity.getImgPathListener != null) {

                        head_img = ChoosePicActivity.getImgPathListener.getImgPath();

                    } else {

                        head_img = JTApplication.jtPreferences.readHeadPath();
                        Log.e("TAG", JTApplication.jtPreferences.readHeadPath());

                    }

                    //走接口 /CPSP-SER2/v1/user/setUserInfo.json?token=当前会话的唯一标示&nickName=昵称&headPic=头像
                    // &emergencyContact=紧急联系人&emergencyContactPhone=紧急联系人电话&driverNum=驾驶证号&driverEffectiveDate=驾驶证有效起始日期&driverEffectiveYear=有效期限
                    final String finalHead_img = head_img;

                    new GetAccountSettings(nick_name, head_img, "", car_num, start_date, validity_period, sex, new AsyCallBack<GetAccountSettings.Info>() {

                        @Override
                        public void onSuccess(String toast, int type, GetAccountSettings.Info info) throws Exception {

                            //传送成功 存储图片路径
                            JTApplication.jtPreferences.saveHeadPath(finalHead_img);

                            //存储 紧急账号(没用！！)
//                            JTApplication.jtPreferences.savePhone2(phone);
                            //存储 昵称
                            JTApplication.jtPreferences.saveNickName(nick_name);
                            //存储驾驶证号
                            JTApplication.jtPreferences.saveDriverNum(car_num);

                            //存储有效起始日期
                            JTApplication.jtPreferences.saveDriverEffectiveDate(start_date);
                            //存储有效期
                            JTApplication.jtPreferences.saveDriverEffectiveYear(validity_period);
                            //性别
                            if (sex.equals("1")) {

                                JTApplication.jtPreferences.saveSex("男");

                            } else if (sex.equals("2")) {

                                JTApplication.jtPreferences.saveSex("女");

                            }

                            //刷新个人信息
                            if (MeFragment.refreshLinster != null) {

                                MeFragment.refreshLinster.refresh();

                            }

                            Toast.makeText(context, "上传成功", Toast.LENGTH_SHORT).show();

                            finish();

                        }
                    }).execute(this);

                }

                break;

            case R.id.head_img1:

                startActivity(new Intent(this, ChoosePicActivity.class)

                        .putExtra("type","0")

                );

                break;

            case R.id.edit_validity_period:

                YouXiaoQiPopup youXiaoQiPopup = new YouXiaoQiPopup(this);

                youXiaoQiPopup.setOnTimeSelectListener(new YouXiaoQiPopup.OnTimeSelectListener() {
                    @Override
                    public void onTimeSelect(String string) {

                        edit_validity_period.setText(string);

                    }
                });

                youXiaoQiPopup.showAtLocation(v, Gravity.BOTTOM, 0, 0);

                break;

        }

    }

    /***
     * 设置图片到控件上
     */
    public abstract class SetHeadPicListener {

        public abstract void setHeadPic(String imageUrl);

    }

}
